//*****************************************************************************
// Vizzini Game Framework (http://vizzini.sourceforge.net)
// Copyright (c) 2004-2009 Vizzini.org
// Admin jmthompson_97@users.sourceforge.net
//
// See the file "LICENSE.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//*****************************************************************************

package org.jfab.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


/**
 * Provides a stream gobbler. Typical usage is to drain the error and output
 * streams when using Runtime.exec().
 *
 * <pre>
   Process process = Runtime.getRuntime().exec(command);

   StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR", false);
   StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT", false);

   errorGobbler.start();
   outputGobbler.start();

   try
   {
       process.waitFor();
   }
   catch (InterruptedException e)
   {
       LOGGER.log(Level.SEVERE, e.getMessage(), e);
   }
 * </pre>
 *
 * @author   Jeffrey M. Thompson
 * @version  v0.3
 * @since    v0.3
 */
class StreamGobbler extends Thread
{
    /** Input stream. */
    private InputStream _inputStream;

    /** Flag indicating if any output was produced. */
    private boolean _isOutputProduced;

    /** Flag indicating whether to produce verbose output. */
    private boolean _isVerbose;

    /** Stream type. */
    private String _type;

    /**
     * Construct this object with the given parameters.
     *
     * @param  inputStream  Input stream.
     * @param  type         Stream type.
     * @param  isVerbose    Flag indicating whether to produce verbose output.
     *
     * @since  v0.3
     */
    StreamGobbler(InputStream inputStream, String type, boolean isVerbose)
    {
        _inputStream = inputStream;
        _type = type;
        _isVerbose = isVerbose;
    }

    /**
     * @return  Return isOutputProduced.
     *
     * @since   v0.3
     */
    public boolean isOutputProduced()
    {
        return _isOutputProduced;
    }

    /**
     * @see  java.lang.Thread#run()
     */
    @Override public void run()
    {
        try
        {
            InputStreamReader isr = new InputStreamReader(_inputStream);
            BufferedReader br = new BufferedReader(isr);
            String line = null;

            while (( line = br.readLine() ) != null)
            {
                _isOutputProduced = true;

                if (_isVerbose)
                {
                    System.out.println(_type + ">" + line);
                }
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
